package com.uxsino.commons.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * PDF生成工具类
 *
 * @Author: jane
 * @Date: 2019/3/4 15:49
 */
public class PdfUtils {

    private static final Logger logger = LoggerFactory.getLogger(PdfUtils.class);

    private static final int DEFAULT_WIDTH = 770;

    public static BaseFont bfChinese;

    static {
        try {
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入段落信息
     *
     * @param document
     * @param string   段落信息
     * @param font     段落字体
     */
    public static void writeParagraph(Document document, String string, Font font, int alignment, BaseColor color, float indentationLeft) {

        try {
            // 字体颜色
            if (Objects.nonNull(color)) {
                font.setColor(color);
            }
            Paragraph paragraph = new Paragraph(string + "\r", font);
            // 左侧缩进
            if (indentationLeft > 0) {
                paragraph.setIndentationLeft(indentationLeft);
            }
            paragraph.setAlignment(alignment);
            document.add(paragraph);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 写入图片
     *
     * @param document
     * @param file      图片流
     * @param alignment 对齐方式
     */
    public static void writeImage(Document document, byte[] file, int alignment) {
        try {
            if (file.length > 0) {
                Image image = Image.getInstance(file);
                image.setAlignment(alignment);
                // 图片缩放比例-暂时处理方式
                float scalePercent = DEFAULT_WIDTH * 100 / image.getWidth();
                if (scalePercent < 100) {
                    scalePercent = 30;
                } else if (scalePercent < 130) {
                    scalePercent *= 0.5;
                } else if (scalePercent < 150) {
                    scalePercent *= 0.4;
                } else {
                    scalePercent *= 0.35;
                }
                image.scalePercent(scalePercent);
                document.add(image);
            }
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入表格数据-表格占页面宽度95%，水平均中、垂直居中
     *
     * @param document
     * @param title_zh   中文表头
     * @param title_en   英文表头
     * @param width      表格相对宽度
     * @param tableDates 表格数据
     */
    public static void writeTable(Document document, String[] title_zh, String[] title_en, int[] width,
                                  JSONArray tableDates, Boolean isNewLine) {
        if (Objects.nonNull(tableDates)) {
            PdfPTable table = new PdfPTable(title_zh.length);
            table.setSplitLate(false);
            table.setSplitRows(true);
            if (!tableDates.isEmpty()) {
                table.setHeaderRows(1);
            }
            try {
                table.setWidths(width);
                // 中文字体格式
                Font dateFont = new Font(bfChinese, 10, Font.NORMAL);
                Font titleFont = new Font(bfChinese, 12, Font.NORMAL);
                table.setWidthPercentage(95); // 占页面宽度比例
                table.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中
                table.setHorizontalAlignment(Element.ALIGN_MIDDLE);// 垂直居中
                // 写入表头
                for (String title : title_zh) {
                    table.addCell(createCell(title, titleFont, 30, 0, 0, new BaseColor(235, 237, 241)));
                }
                // 写入数据
                for (int i = 0; i < tableDates.size(); i++) {
                    JSONObject tableData = tableDates.getJSONObject(i);
                    for (int j = 0; j < title_en.length; j++) {
                        String title = title_en[j];
                        int multiplier = 0;
                        String value = tableData.getString(title);
                        if (StringUtils.isNotEmpty(tableData.getString(title))) {
                            value = value.replaceAll("\\s*", "");
                            multiplier = (value.length() / (width[j] - 4)) + 1;
                        }
                        if (StringUtils.isNotEmpty(value) && value.length() / width[j] > 50) {
                            value = value.substring(0, 39 * width[j]) + "...";
                            multiplier = 40;
                        }
                        table.addCell(createCell(value, dateFont,
                                multiplier > 1 ? multiplier * 9 : 20, 0, 0, null));
                    }
                }
                document.add(table);
                // 换行
                if (isNewLine) {
                    document.add(new Paragraph("\r"));
                }

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeTableMergeCellByVertical(Document document, String[] title_zh, String[] title_en, int[] width,
                                                     JSONArray tableDates, int rowSpan, int colSpan, int mergeColNum) {
        if (Objects.nonNull(tableDates)) {
            PdfPTable table = new PdfPTable(title_zh.length);
            table.setHeaderRows(1);
            try {
                table.setWidths(width);
                // 中文字体格式
                Font dateFont = new Font(bfChinese, 10, Font.NORMAL);
                Font titleFont = new Font(bfChinese, 12, Font.BOLD);
                table.setWidthPercentage(95); // 占页面宽度比例
                table.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中
                // 写入表头
                for (String title : title_zh) {
                    table.addCell(createCell(title, titleFont, 30, 0, 0, BaseColor.LIGHT_GRAY));
                }
                // 写入数据
                boolean isMerged = false;
                for (int i = 0; i < tableDates.size(); i++) {
                    JSONObject tableData = tableDates.getJSONObject(i);
                    for (int j = 0; j < title_en.length; j++) {
                        String value = tableData.getString(title_en[j]);
                        int multiplier = 0;
                        if (StringUtils.isNotEmpty(tableData.getString(title_en[j]))) {
                            multiplier = (tableData.getString(title_en[j]).length() / (width[(j % (width.length))] - 4)) + 1;
                            value.trim();
                        }
                        if (j == mergeColNum) {
                            if (!isMerged) {
                                table.addCell(createCell(value, dateFont, 30, rowSpan, colSpan, null));
                                isMerged = true;
                            }
                        } else {
                            table.addCell(createCell(value, dateFont, multiplier > 1 ? multiplier * 15 : 20,
                                    1, colSpan, null));
                        }
                    }
                }
                document.add(table);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * PDF创建表格
     *
     * @param string 表格内容
     * @param font   内容字体风格
     * @param height 单元格高度
     * @return PdfPCell 表格对象
     */
    public static PdfPCell createCell(String string, Font font, int height, int rowSpan, int colSpan, BaseColor baseColor) {
        PdfPCell cell = new PdfPCell(new Paragraph(string, font));
        cell.setUseAscender(true);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);// 垂直居中
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 水平居中
        if (height > 0) {
            cell.setFixedHeight(height);
        } else {
            cell.setFixedHeight(20);
        }
        if (rowSpan > 0) {
            cell.setRowspan(rowSpan);
        }
        if (colSpan > 0) {
            cell.setColspan(colSpan);
        }
        cell.setPaddingLeft(3);
        if (Objects.nonNull(baseColor)) {
            cell.setBackgroundColor(baseColor);
        }
        return cell;
    }

}
